package org.springblade.modules.resource.builder.oss;

import com.google.api.client.util.Value;
import io.minio.MinioClient;
import io.minio.ServerSideEncryption;
import org.springblade.core.oss.minio.MinioTemplate;
import org.springblade.core.oss.model.BladeFile;
import org.springblade.core.oss.props.OssProperties;
import org.springblade.core.oss.rule.BladeOssRule;
import org.springblade.core.oss.rule.OssRule;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.StringPool;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.resource.entity.Oss;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Map;

public class UploadFileBuilder extends MinioTemplate {

	private MinioClient client;
	private OssRule ossRule;
	private OssProperties ossProperties;

	public UploadFileBuilder(MinioClient client, OssRule ossRule, OssProperties ossProperties) {
		super(client, ossRule, ossProperties);
		this.client = client;
		this.ossProperties = ossProperties;
		this.ossRule = ossRule;
	}

	@Override
	public BladeFile putFile(String bucketName, String fileName, InputStream stream, String contentType) {
		try {
			String filePath = "upload/" + DateUtil.today() + "/" + StringUtil.randomUUID() + "/" + fileName;
			this.makeBucket(bucketName);
			client.putObject(this.ossRule.bucketName(bucketName), filePath, stream, (long)stream.available(), (Map)null, (ServerSideEncryption)null, contentType);
			BladeFile file = new BladeFile();
			file.setOriginalName(filePath);
			file.setName(filePath);
			file.setDomain(this.getOssHost(bucketName));
			file.setLink(this.fileLink(bucketName, filePath));
			return file;
		} catch (Throwable var7) {
			var7.printStackTrace();
		}
		return null;
	}

	public static BladeFile handlePutFile(String fileName, MultipartFile indexFile, OssBuilder ossBuilder) {
		try {
			Oss oss = ossBuilder.getOss(AuthUtil.getTenantId(), StringPool.EMPTY);
			MinioClient minioClient = new MinioClient(oss.getEndpoint(),oss.getAccessKey(),oss.getSecretKey());
			OssProperties ossProperties = new OssProperties();
			ossProperties.setEndpoint(oss.getEndpoint());
			ossProperties.setAccessKey(oss.getAccessKey());
			ossProperties.setSecretKey(oss.getSecretKey());
			ossProperties.setBucketName(oss.getBucketName());
			BladeOssRule ossRule = new BladeOssRule(Boolean.TRUE);
			UploadFileBuilder builder = new UploadFileBuilder(minioClient, ossRule, ossProperties);
			return builder.putFile(ossProperties.getBucketName(), fileName, indexFile.getInputStream(), "application/octet-stream");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void removeFile(String bucketName, String fileName) {

	}
}
